package com.gomoku;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class JoinGameFrame extends JFrame {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private GameLogic gameLogic;
    private boolean isClientTurn;

    private JButton[][] boardButtons;
    private JLabel statusLabel;

    public JoinGameFrame() {
        gameLogic = new GameLogic();
        isClientTurn = false;

        setTitle("客户端 - 联机五子棋");
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        initComponents();
        connectToServer();
    }

    private void initComponents() {
        JPanel boardPanel = new JPanel(new GridLayout(GameLogic.BOARD_SIZE, GameLogic.BOARD_SIZE));
        boardButtons = new JButton[GameLogic.BOARD_SIZE][GameLogic.BOARD_SIZE];

        for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
            for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(40, 40));
                button.setOpaque(true);
                button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                button.setBackground(new Color(220, 179, 92));

                final int row = i;
                final int col = j;
                button.addActionListener(e -> handleButtonClick(row, col));

                boardButtons[i][j] = button;
                boardPanel.add(button);
            }
        }

        statusLabel = new JLabel("正在连接服务器...", JLabel.CENTER);
        statusLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        JButton restartButton = new JButton("重新开始");
        restartButton.addActionListener(e -> sendMove(-1, -1));

        JButton backButton = new JButton("返回主菜单");
        backButton.addActionListener(e -> {
            dispose();
            try {
                if (socket != null) socket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            new MainMenu().setVisible(true);
        });

        JPanel controlPanel = new JPanel(new GridLayout(1, 2));
        controlPanel.add(restartButton);
        controlPanel.add(backButton);

        add(boardPanel, BorderLayout.CENTER);
        add(statusLabel, BorderLayout.NORTH);
        add(controlPanel, BorderLayout.SOUTH);
    }

    private void handleButtonClick(int row, int col) {
        if (isClientTurn && gameLogic.makeMove(row, col)) {
            updateBoard();
            sendMove(row, col);

            if (gameLogic.isGameOver()) {
                updateStatus();
            } else {
                isClientTurn = false;
                updateStatus();
            }
        }
    }

    private void updateBoard() {
        int[][] board = gameLogic.getBoard();

        for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
            for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                Color color;
                switch (board[i][j]) {
                    case 1: color = Color.BLACK; break;
                    case 2: color = Color.WHITE; break;
                    default: color = new Color(220, 179, 92); break;
                }
                boardButtons[i][j].setBackground(color);
            }
        }
    }

    private void updateStatus() {
        if (gameLogic.isGameOver()) {
            String winner = gameLogic.getCurrentPlayer() == 1 ? "黑方(主机)" : "白方(客户端)";
            statusLabel.setText("游戏结束 - " + winner + "获胜");
        } else {
            String turn = isClientTurn ? "客户端" : "主机";
            statusLabel.setText(turn + "回合 - 等待对方行动...");
        }
    }

    private void sendMove(int row, int col) {
        try {
            out.println(row + "," + col);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "连接已断开", "错误", JOptionPane.ERROR_MESSAGE);
            dispose();
            new MainMenu().setVisible(true);
        }
    }

    private void connectToServer() {
        new Thread(() -> {
            try {
                socket = new Socket("localhost", 12345);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                statusLabel.setText("已连接到主机 - 等待游戏开始");

                // 开始监听主机消息
                new Thread(() -> {
                    try {
                        String inputLine;
                        while ((inputLine = in.readLine()) != null) {
                            if (inputLine.equals("-1,-1")) { // 重新开始信号
                                gameLogic.resetGame();
                                isClientTurn = false;
                                SwingUtilities.invokeLater(() -> {
                                    updateBoard();
                                    updateStatus();
                                });
                                continue;
                            }

                            String[] parts = inputLine.split(",");
                            int row = Integer.parseInt(parts[0]);
                            int col = Integer.parseInt(parts[1]);

                            if (row != -1 && col != -1) {
                                gameLogic.makeMove(row, col);

                                SwingUtilities.invokeLater(() -> {
                                    updateBoard();

                                    if (gameLogic.isGameOver()) {
                                        updateStatus();
                                    } else {
                                        isClientTurn = true;
                                        updateStatus();
                                    }
                                });
                            }
                        }
                    } catch (IOException e) {
                        JOptionPane.showMessageDialog(this, "主机断开连接", "错误", JOptionPane.ERROR_MESSAGE);
                        SwingUtilities.invokeLater(() -> {
                            dispose();
                            new MainMenu().setVisible(true);
                        });
                    }
                }).start();

            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "无法连接到主机: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                SwingUtilities.invokeLater(() -> {
                    dispose();
                    new MainMenu().setVisible(true);
                });
            }
        }).start();
    }
}